#include <lversion.h>
#if L_VERSION_MODULE_SCENE_OBJ == 120104

#include "_lsceneObj_120104.h"

#include <lcollisionDetector.h>
#include <lcollisionResult.h>
using namespace llib;
using namespace llib::geom;
using namespace llib::collision;

#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;


void SceneObj::Init( vector<Vec3f>& vertexList, vector<Vec3i>& faceVertexIndexList )
{
    /* build up mesh */
    _mesh.SetModelData(vertexList, faceVertexIndexList);

    /* build up tree */
    _tree.Init(_mesh);

    /* set up collision flag */
    _collision = vector<Boolean>(_mesh.GetFaceNum(), FALSE);
}

void SceneObj::UpdateTree()
{
    BVTreeIter* iter = _tree.CreateIter(BVTreeIter::Postorder);
    BVNode* node = iter->Next();
    while(node != NULL) {
        node->Update();
        node = iter->Next();
    }
    delete iter;
}

void SceneObj::CollisionDetect( SceneObj& first, SceneObj& second )
{
    // prepare data store
    CollisionResult cr;
    fill(first._collision.begin(),first._collision.end(),FALSE);
    fill(second._collision.begin(),second._collision.end(),FALSE);

    // the collision process
    BVNode* firstRoot = first._tree.GetRoot();
    BVNode* secondRoot = second._tree.GetRoot();
    CollisionDetector::CollisionDetect(firstRoot, secondRoot, &cr);

    // update _collision
    Int32 faceNum = first._mesh.GetFaceNum();
    FOR(F,0,faceNum) {
        if(cr.CheckCollide(first._mesh.GetFace(F)))
            first._collision[F] = TRUE;
    }
    faceNum = second._mesh.GetFaceNum();
    FOR(F,0,faceNum) {
        if(cr.CheckCollide(second._mesh.GetFace(F)))
            second._collision[F] = TRUE;
    }
}

void SceneObj::SelfCollisonDetect( SceneObj& obj )
{
    // prepare data store
    CollisionResult cr;
    fill(obj._collision.begin(),obj._collision.end(),FALSE);

    // the collision process
    CollisionDetector::SelfCollisionDetect(obj._tree.GetRoot(), &cr);

    // update _collision
    Int32 faceNum = obj._mesh.GetFaceNum();
    FOR(F,0,faceNum) {
        if(cr.CheckCollide(obj._mesh.GetFace(F)))
            obj._collision[F] = TRUE;
    }
}


#endif
